//
//  BwtNativeExpressAd.m
//  bwt_ad_flutter
//
//  Created by ciba on 2024/10/11.
//

#import "BwtNativeExpressAd.h"
#import "BwtAdLogManager.h"

@interface BwtNativeExpressAd ()<CXHAdSDKNativeExpressAdDelegate>
@property (nonatomic) bool isAdExposed;
@property (nonatomic) bool isAdClosed;
@property (nonatomic) CXHAdSDKNativeExpressAd *nativeExpressAd;

@end

@implementation BwtNativeExpressAd

/// 接到Flutter消息，开始加载信息流广告
- (void)loadNativeExpressAd {
    if (self.nativeExpressAd) {
        return;
    }
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告加载前检查, adId: %@", _adParams.adId];
    if (_isRequestIdfa && @available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            if ([NSThread isMainThread]) {
                [self innerLoadNativeExpressAd ];
            } else {
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // 非主线程，将UI操作切换到主线程进行，请求广告
                    [self innerLoadNativeExpressAd ];
                });
            }
        }];
    } else {
        [self innerLoadNativeExpressAd];
    }
}

/// 真正的请求信息流广告
- (void) innerLoadNativeExpressAd {
    if (!self.nativeExpressAd) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIViewController *rvc = window.rootViewController;
        
        self.nativeExpressAd = [[CXHAdSDKNativeExpressAd alloc]initWithAdSize:CGSizeMake([_adParams.adWidth floatValue], 10)];
        self.nativeExpressAd.delegate = self;
        self.nativeExpressAd.controller = rvc;
        self.nativeExpressAd.posId = _adParams.posId;
    }
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"正在加载信息流模板广告, adId: %@", _adParams.adId];
    [self.nativeExpressAd load:1];
}


/// 接到Flutter消息，释放插屏广告
- (void)releaseAd {
    if (self.nativeExpressAd) {
        self.nativeExpressAd = nil;
        _nativeExpressAdView = nil;
        
        [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告已释放, adId: %@", _adParams.adId];
    }
}

#pragma mark - CXHAdSDKNativeExpressAdDelegate
/**
 信息流广告请求成功

 @param nativeAd 广告实例
 @param adViewArray 广告模板集合
 */
- (void)CXH_nativeAdSucessToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                     adViewArray:(NSArray<__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *> *)adViewArray{
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告加载成功, adId: %@", _adParams.adId];
    for (UIView<CXHAdapterNativeExpressAdViewDelegate> *adView in adViewArray) {
        [adView render];
    }
}

/**
 信息流广告请求失败

 @param nativeAd 广告实例
 @param error 请求错误描述
 */
- (void)CXH_nativeAdFailToLoad:(CXHAdSDKNativeExpressAd *)nativeAd
                         error:(NSError *)error{
    NSString *message = [error localizedDescription];
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告加载失败, adId: %@, error: %@", _adParams.adId, message];
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:message];
    
    [self releaseAd];
}

/**
 信息流广告渲染成功

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistSuccess:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告渲染成功, adId: %@", _adParams.adId];
    
    _nativeExpressAdView = adView;
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadEvent:_adParams];
    
    NSMutableDictionary *extras = [[NSMutableDictionary alloc] initWithCapacity:0];
    [extras setObject:@(adView.frame.size.width) forKey:@"adWidth"];
    [extras setObject:@(adView.frame.size.height) forKey:@"adHeight"];
    [bwtAdEventManager postOnAdMeasuredEvent:_adParams extras: extras];
}

/**
 信息流广告渲染失败

 @param adView 广告视图
 */
- (void)CXH_nativeAdViewRenderOrRegistFail:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    NSString *message = @"广告渲染失败了";
    
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告渲染失败, adId: %@, error: %@", _adParams.adId, message];
    
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdLoadFailedEvent:_adParams message:message];
    
    [self releaseAd];
}

/**
 信息流广告被点击

 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClicked:(CXHAdSDKNativeExpressAd *)nativeAd
                     adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView loadingPageURL:(NSString *)loadingPageURL{
    [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告被点击, adId: %@", _adParams.adId];
    /// 通知Flutter端
    BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
    [bwtAdEventManager postOnAdClickEvent:_adParams];
}

/**
 信息流广告被关闭
 
 @param nativeAd 广告模板
 */
- (void)CXH_nativeAdClose:(CXHAdSDKNativeExpressAd *)nativeAd
                   adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    if (!self.isAdClosed) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告被关闭, adId: %@", _adParams.adId];
        self.isAdClosed = YES;
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdCloseEvent:_adParams];
    }
    
    [self releaseAd];
}

/**
 信息流广告被展示
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdExposure:(CXHAdSDKNativeExpressAd *)nativeAd
                      adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    if (!self.isAdExposed) {
        [[BwtAdLogManager getBwtAdLogManager] log:@"信息流模板广告被展示, adId: %@", _adParams.adId];
        self.isAdExposed = YES;
        /// 通知Flutter端
        BwtAdEventManager *bwtAdEventManager = [BwtAdEventManager getBwtAdEventManager];
        [bwtAdEventManager postOnAdExposeEvent:_adParams];
    }
}

/**
 信息流广告落地页被关闭
 
 @param nativeAd 广告实例
 */
- (void)CXH_nativeAdCloseLandingPage:(CXHAdSDKNativeExpressAd *)nativeAd
                              adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}
@end
